package com.teacher.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.common.ResultCode;
import com.teacher.mapper.PerStudentMapper;
import com.teacher.mapper.PerTeacherMapper;
import com.teacher.mapper.TermMapper;
import com.teacher.pojo.dto.file.FileAddDto;
import com.teacher.pojo.dto.moraleducation.MoralEducationAddDto;
import com.teacher.pojo.dto.moraleducation.MoralEducationUpdateDto;
import com.teacher.pojo.entity.Flow;
import com.teacher.pojo.entity.MoralEducationTask;
import com.teacher.mapper.MoralEducationTaskMapper;
import com.teacher.pojo.enums.FlowApproveType;
import com.teacher.pojo.enums.FlowType;
import com.teacher.pojo.vo.moraleducationtask.MoralEducationGetVo;
import com.teacher.service.IFlowService;
import com.teacher.service.IMoralEducationTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 德育素质审批表 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2021-08-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MoralEducationTaskServiceImpl extends ServiceImpl<MoralEducationTaskMapper, MoralEducationTask> implements IMoralEducationTaskService {

    @Autowired
    private IFlowService iFlowService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PerTeacherMapper perTeacherMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private TermMapper termMapper;

    @Autowired
    private PerStudentMapper perStudentMapper;

    /**
     * 发起德育素质审批流程
     *
     * @param dto
     * @return
     */
    @Override
    public CommonResult<String> add(MoralEducationAddDto dto) {
        String studentKey = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        if (studentKey == null) {
            return CommonResult.failed("非法用户");
        }
        String monitorKey = perTeacherMapper.getMonitorByStudentKey(studentKey);
        if (StrUtil.isEmpty(monitorKey)) {
            return CommonResult.failed("未找到下一节审批人");
        }

        Long flowId = iFlowService.createFlow(studentKey, monitorKey, FlowType.MORAL_EDUCATION.getType());

        if (flowId == null) {
            return CommonResult.failed("启动失败");
        }

        MoralEducationTask moralEducationTask = new MoralEducationTask();
        moralEducationTask.setFlowId(flowId);
        moralEducationTask.setRemark(dto.getRemark());
        moralEducationTask.setFiles(JSONUtil.toJsonStr(dto.getFiles()));
        moralEducationTask.setType(dto.getType());
        moralEducationTask.setStudentKey(studentKey);
        moralEducationTask.setTermId(termMapper.getCurrentTerm());
        if (this.save(moralEducationTask)) {
            return CommonResult.success("提交成功");
        }
        return CommonResult.failed("提交失败");
    }

    /**
     * 更新流程
     *
     * @param dto
     * @return
     */
    @Override
    public CommonResult<String> updateInfo(MoralEducationUpdateDto dto) {
        CommonResult<String> result = iFlowService.reStart(dto.getId());
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            return result;
        }

        MoralEducationTask moralEducationTask = this.getOne(new QueryWrapper<MoralEducationTask>().lambda()
                .eq(MoralEducationTask::getFlowId, dto.getId()).last("limit 1"));
        moralEducationTask.setRemark(dto.getRemark());
        moralEducationTask.setFiles(JSONUtil.toJsonStr(dto.getFiles()));
        moralEducationTask.setType(dto.getType());
        if (this.updateById(moralEducationTask)) {
            return CommonResult.success("提交成功");
        }
        return CommonResult.failed("提交失败");
    }

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<MoralEducationGetVo> getDetails(Long id) {
        MoralEducationTask moralEducationTask = this.getOne(new QueryWrapper<MoralEducationTask>().lambda()
                .eq(MoralEducationTask::getFlowId, id));
        if (moralEducationTask == null) {
            return CommonResult.failed("流程不存在");
        }
        MoralEducationGetVo vo = new MoralEducationGetVo();
        BeanUtils.copyProperties(moralEducationTask, vo);
        vo.setCreateTime(moralEducationTask.getCreateTime());
        vo.setFiles(JSONUtil.toList(JSONUtil.parseArray(moralEducationTask.getFiles()), FileAddDto.class));
        vo.setFlowApproveDetailsVos(iFlowService.getApproveDetails(id));
        vo.setStudentName(perStudentMapper.getNameByStudentKey(moralEducationTask.getStudentKey()));

        Flow flow = iFlowService.getById(id);

        // 是否可取消
        if (flow.getApplyUsername().equals(jwtTokenUtil.getUsernameByRequest(httpServletRequest))
                && flow.getStatus().equals(FlowApproveType.WAIT.getCode())) {
            vo.setCanCancel(true);
        } else {
            vo.setCanCancel(false);
        }

        // 是否可审批
        if (flow.getCurrentApproveUsername().equals(jwtTokenUtil.getUsernameByRequest(httpServletRequest))) {
            vo.setCanApprove(true);
        } else {
            vo.setCanApprove(false);
        }
        // 是否可重新提交
        if (flow.getApplyUsername().equals(jwtTokenUtil.getUsernameByRequest(httpServletRequest))
                && flow.getStatus().equals(FlowApproveType.BACK_UPDATE.getCode())) {
            vo.setCanBack(true);
        } else {
            vo.setCanBack(false);
        }
        return CommonResult.success(vo);
    }
}
